package cn.jdemo.juc.thread;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TransmittableThreadLocal -- 阿里的
 *
 * 父子线程传递 - 线程池情况下
 */
public class DemoTransParm05 {

    public static void main(String[] args) throws InterruptedException {
        test01();
        // test02();
    }

    /**
     * TransmittableThreadLocal
     *
     * cuurThread_pool-1-thread-1
     * 租户数据1
     * cuurThread_pool-1-thread-1
     * 租户数据2
     */
    public static void test02() throws InterruptedException {
        TransmittableThreadLocal<String> ttl = new TransmittableThreadLocal<>();
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        threadPool = TtlExecutors.getTtlExecutorService(threadPool);//  ttl包装下线程池

        ttl.set("租户数据1");
        threadPool.submit(()->{
            System.out.println("cuurThread_" + Thread.currentThread().getName());
            System.out.println(ttl.get());
        });
        Thread.sleep(10);

        ttl.set("租户数据2");
        threadPool.submit(()->{
            System.out.println("cuurThread_" + Thread.currentThread().getName());
            System.out.println(ttl.get());
        });
    }

    /**
     * 输出内容（首次线程创建可以传递，之后线程复用无法传递）:
     * cuurThread_pool-1-thread-2
     * 租户数据1
     * cuurThread_pool-1-thread-2
     * 租户数据1
     * cuurThread_pool-1-thread-1
     * 租户数据3
     */
    public static void test01() throws InterruptedException {
        ThreadLocal<String> ttl = new InheritableThreadLocal<>();
        ExecutorService threadPool = Executors.newFixedThreadPool(2);

        threadPool.submit(()->{
            ttl.set("租户数据1");
            threadPool.submit(()->{
                System.out.println("cuurThread_" + Thread.currentThread().getName());
                System.out.println(ttl.get());
            });

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            ttl.set("租户数据2");
            threadPool.submit(()->{
                System.out.println("cuurThread_" + Thread.currentThread().getName());
                System.out.println(ttl.get());
            });

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            ttl.set("租户数据3");
            threadPool.submit(()->{
                System.out.println("cuurThread_" + Thread.currentThread().getName());
                System.out.println(ttl.get());
            });
        });
    }
}
